package edu.indiana.d2i.vmm;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class SigiriHTRCConfiguration implements Iterable<SigiriHTRCConfiguration.SigiriHTRCPropertyEntry> {
	private static final Log logger = LogFactory.getLog(SigiriHTRCConfiguration.class);
	private Map<String, String> properties = new HashMap<String, String>();
	
	public static class SigiriHTRCPropertyEntry {
		Map<String, String> attributes = new HashMap<String, String>();
	}

	private void loadResources(String filename) {
		InputStream inStream = getClass().getClassLoader().getResourceAsStream(filename);
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			docBuilderFactory.setIgnoringComments(true);
			DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();		    
		    Document doc = builder.parse(inStream);
		    Element root = doc.getDocumentElement();
		    NodeList props = root.getChildNodes();
	        String attr = null;
	        String value = null;
		    for (int j = 0; j < props.getLength(); j++) {
		    	Node propNode = props.item(j);
		        if (!(propNode instanceof Element)) continue;
		        Element prop = (Element)propNode;
		    	NodeList fields = prop.getChildNodes();
			    for (int i = 0; i < fields.getLength(); i++) {
			    	if (!(fields.item(i) instanceof Element)) continue;
			    	Element field = (Element)fields.item(i);
			    	if ("name".equals(field.getTagName())) 
			    		attr = field.getFirstChild().getNodeValue();
			    	if ("value".equals(field.getTagName())) 
			    		value = field.getFirstChild().getNodeValue();
			    }
			    if (attr != null && value != null) properties.put(attr, value);
		    }
		} catch (ParserConfigurationException e) {
			logger.fatal(e);
			throw new RuntimeException(e);
		} catch (SAXException e) {
			logger.fatal(e);
			throw new RuntimeException(e);
		} catch (IOException e) {
			logger.fatal(e);
			throw new RuntimeException(e);
		}
	}
	
	public SigiriHTRCConfiguration() {
		loadResources("vmm-core.xml");
	}
	
	public String getProperty(String attribute) {
		return properties.get(attribute);
	}

	@Override
	public Iterator<SigiriHTRCConfiguration.SigiriHTRCPropertyEntry> iterator() {
		
		return null;
	}
}
